
public class Leetcode1763 {

    public static void main(String[] args) {
        System.out.println(longestNiceSubstring("YazaAay"));
    }

    public static String longestNiceSubstring(String s) {
        int n = s.length();
        int startIndex = -1;
        int maxLength = 0;
        for (int i = 0; i < n; i++) {
            int big = 0;
            int small = 0;
            for (int j = i; j < n; j++) {
                char c = s.charAt(j);
                if (c >= 'a' && c <= 'z') {
                    small |= (1 << (c - 'a'));
                } else {
                    big |= (1 << (c - 'A'));
                }

                if (big == small && j - i + 1 > maxLength) {
                    startIndex = i;
                    maxLength = j - i + 1;
                }
            }
        }

        return startIndex == -1 ? "" : s.substring(startIndex, startIndex + maxLength);
    }


}
